package main

import (
	//"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"github.com/davyxu/ulog"
	"encoding/base64"
	//"io/ioutil"
	"os"
)

var upGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func readPicture(data []byte){
	
	dist, _ := base64.StdEncoding.DecodeString(string(data))

	f, _ := os.OpenFile("xx.jpg", os.O_RDWR|os.O_CREATE, os.ModePerm)
	defer f.Close()
	f.Write(dist)

}

func readNewFile(data []byte) {

	f, _ := os.OpenFile("xx.jpg", os.O_RDWR|os.O_CREATE, os.ModePerm)
	defer f.Close()
	f.Write(data)

}

func readFile(resp http.ResponseWriter, req *http.Request){

	ws, err := upGrader.Upgrade(resp, req, nil)
	if err != nil {
		return
	}

	defer ws.Close() 

	for {

		mt, message, err := ws.ReadMessage()
		if err != nil {
			break
		}

		switch mt {
		case websocket.TextMessage:

			ulog.Infoln("TextMessage: ", string(message))
		
		case websocket.BinaryMessage:

			ulog.Infoln("BinaryMessage: ", string(message))

			readPicture(message)
			//readNewFile(message)

		default:
			ulog.Infoln("aaa")
		}
		
	}

}

func main(){

	http.HandleFunc("/echo", readFile)
	http.ListenAndServe("localhost:8080", nil)

}